package com.archerdu.demo;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/applications.xml")
public class SpringTestDemo {

	private static Logger LOG = Logger.getLogger(SpringTestDemo.class);

	@Autowired
	private DemoDao demoDao;

	@Autowired
	private SessionFactory sessionFactory;

	@Test
	public void testIoc() {
		LOG.debug("demoDao is : " + demoDao);
		assertNotNull(demoDao);
	}

	@Test
	public void testHibernateSession() {
		LOG.debug("sessionFactory is : " + sessionFactory);
		assertNotNull(sessionFactory.openSession());
	}

	@SuppressWarnings("rawtypes")
	@Test
	public void testSql() {
		Session session = sessionFactory.openSession();
		Transaction ts = null;
		ts = session.beginTransaction();
		String sql = "select * from web.tb_menu";
		SQLQuery query = session.createSQLQuery(sql);
		List list = query.list();
		ts.commit();
		LOG.debug("list.size() is " + list.size());
		assertNotNull(list.size() > 0);
	}

	@Test
	public void testJDBC() {
		LOG.debug("==============\n\r method is running");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(
					"jdbc:mysql://127.0.0.1:3306/web", "root", "123456");
			PreparedStatement ps = conn
					.prepareStatement("select * from web.tb_menu");
			ResultSet rs = ps.executeQuery();
			LOG.debug("==============\n\r rows is " + rs.getRow());
			assertTrue(rs.getRow() > -1);
			conn.close();
		} catch (ClassNotFoundException e) {
			LOG.error(e.getMessage(), e);
		} catch (SQLException e) {
			LOG.error(e.getMessage(), e);
		}
	}

	public DemoDao getDemoDao() {
		return demoDao;
	}

	public void setDemoDao(DemoDao demoDao) {
		this.demoDao = demoDao;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
